package com.hrg.rds.biz.runner;

import com.hrg.rds.biz.config.RdsConfiguration;
import com.hrg.rds.biz.waybill.domain.instance.WaybillInstance;
import com.hrg.rds.biz.waybill.domain.instance.WaybillInstanceDto;
import com.hrg.rds.biz.waybill.domain.instance.WaybillInstanceStatus;
import com.hrg.rds.biz.waybill.domain.instance.WaybillInstanceVo;
import com.hrg.rds.biz.waybill.service.WaybillInstanceService;
import com.hrg.rds.infra.async.executor.Async;
import com.hrg.rds.infra.executor.ExecutorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
// 重启运单实例，在系统启动完成后执行一次
public class RestartWaybillInstanceRunner implements CommandLineRunner {
	// 若该方法抛出异常，Spring Boot 会将其视为启动失败，进而停止应用。

	@Autowired
	private WaybillInstanceService waybillInstanceService;

	@Override
	public void run(String... args) {
		// 设置为重启异常，然后人工干预
		WaybillInstanceDto waybillInstanceDto = new WaybillInstanceDto();
		waybillInstanceDto.setWaybillInstanceStatusList(Arrays.asList(WaybillInstanceStatus.ToBeDispatched, WaybillInstanceStatus.Executing));
		List<WaybillInstanceVo> waybillInstanceVos = waybillInstanceService.selectList(waybillInstanceDto);
		for (WaybillInstanceVo waybillInstanceVo : waybillInstanceVos) {
			WaybillInstance waybillInstance = new WaybillInstance();
			waybillInstance.setId(waybillInstanceVo.getId());
			waybillInstance.setWaybillInstanceStatus(WaybillInstanceStatus.Exception);
			waybillInstance.setRemark("重启异常！");
			waybillInstanceService.updateById(waybillInstance);
		}
		RdsConfiguration.IfWaybillReadyOnRestart = true;
	}
}
